using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Data.SqlClient;

using WXWorkSvc.Common.Data;

namespace WXWorkSvc.Common.Pages.Logger;

public class DetailModel : PageModel
{
    private readonly SqlServerLoggerProcessor service;
    public DetailModel([FromServices] SqlServerLoggerProcessor svc)
    {
        this.service = svc;

    }
    [BindProperty]
    public int Offset { get; set; }
    [BindProperty]
    public TLogger Item { get; set; } = default!;
    public async Task OnGet(long id, int offset = 0)
    {
        var sql = "SELECT top 1 [Id],[Dt],[Name],[LogLevel],[Msg] FROM [dbo].[Loggers] where ";

        if (offset == 0)
            sql += $"id={id} and appid={service.AppId}";
        else if (offset == 1)
            sql += $"id<{id} and appid={service.AppId} order by id desc";
        else
            sql += $"id>{id} and appid={service.AppId} order by id";
        using var cn = new SqlConnection(service.ConnectionString);
        var cmd = cn.CreateCommand();
        cmd.CommandText = sql;
        await cn.OpenAsync();
        using var dr = await cmd.ExecuteReaderAsync();
        if (dr.Read())
            Item = new TLogger()
            {
                Id = dr.GetInt64(0),
                Dt = dr.GetDateTime(1),
                Name = dr.GetString(2),
                LogLevel = (LogLevel)dr.GetInt32(3),
                Msg = dr.GetString(4)
            };
        else
            Item = new();
        dr.Close();
        cn.Close();
    }
    public async Task<IActionResult> OnPostAsync()
    {
        if (Offset == 0)
        {
            using var cn = new SqlConnection(service.ConnectionString);
            var cmd = cn.CreateCommand();
            cmd.CommandText = $"delete loggers where id={Item.Id} && appid={service.AppId}";
            await cn.OpenAsync();
            await cmd.ExecuteNonQueryAsync();
            await cn.CloseAsync();
            Offset = 1;
        }
        return RedirectToPage("./Detail", new { Item.Id, Offset });

    }
}
